package zuo.algo.c08;

import zuo.algo.data.graph.Graph;
import zuo.algo.data.graph.Node;
import zuo.algo.util.GraphUtils;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;

/**
 * 00:40-图的宽度优先遍历
 * 00:50-图的深度优先遍历
 */
public class GraphTraverse {

    public static void width(Node head) {
        LinkedList<Node> queue = new LinkedList<>();
        Set<Node> set = new HashSet<>();

        queue.add(head);
        set.add(head);
        Node levelEnd = head;
        while (!queue.isEmpty()) {
            Node node = queue.pop();
            System.out.print(node.value + " ");
            for (Node next : node.nexts) {
                if (set.contains(next)) {
                    continue;
                }
                set.add(next);
                queue.add(next);
            }
            if (levelEnd == node) {
                System.out.println();
                if (queue.isEmpty()) {
                    continue;
                }
                levelEnd = queue.getLast();
            }
        }
    }

    public static void depth(Node head) {
        LinkedList<Node> stack = new LinkedList<>();
        Set<Node> set = new HashSet<>();

        stack.push(head);
        set.add(head);

        while (!stack.isEmpty()) {
            Node node = stack.pop();
            Node level = null;
            for (Node next : node.nexts) {
                if (!set.contains(next)) {
                    level = next;
                    break;
                }
            }
            if (level != null) {
                stack.push(node);
                stack.push(level);
                set.add(level);
            } else {
                System.out.println(node.value);
            }
        }
    }

    public static void main(String[] args) {
        int[][] matrix = {
                {0, 1, 1, 1, 0, 0, 0, 0},
                {1, 0, 1, 0, 0, 0, 0, 0},
                {1, 1, 0, 1, 1, 1, 0, 0},
                {1, 0, 1, 0, 0, 0, 0, 0},
                {0, 1, 0, 0, 0, 0, 0, 0},
                {0, 1, 0, 0, 0, 0, 1, 1},
                {0, 0, 0, 0, 0, 1, 0, 0},
                {0, 0, 0, 0, 0, 1, 0, 0},
        };
        Graph graph = GraphUtils.createGraph1(matrix);
        width(graph.nodes.get(0));
        depth(graph.nodes.get(0));
    }
}
